package at.moop.eneo;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;
import at.moop.eneo.model.Point;
import at.moop.eneo.util.Properties;

/**
 * The Retriever connects to the server and submits the point.
 *
 */
public class PointSubmitter {
    
    private final String TAG = "PointSubmitter";
    private String username;
    private String password;
	private DefaultHttpClient client = new DefaultHttpClient();
	
	public PointSubmitter(String user, String pass){
		this.username = user;
		this.password = pass;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * Submit the point
	 * @param point The point which should be submitted
	 * @return The result returned by the server
	 */
    public String retrieve(Point point) {
    	String default_url =  Properties.DEFAULT_SERVER + "insert.php?x=%s&y=%s&user=%s&time=%s&pass=%s";
        String url = String.format(default_url, String.valueOf(point.getLatitude()), String.valueOf(point.getLongitude()), username, String.valueOf(point.getDateFetched()), password);        

        HttpGet get = new HttpGet(url);

        try {

            HttpResponse getResponse = client.execute(get);
            HttpEntity getResponseEntity = getResponse.getEntity();

            if (getResponseEntity != null) {
                String response = EntityUtils.toString(getResponseEntity);
                Log.d(TAG, response);
                return response;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

}